package middleware

import (
	"encoding/json"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"micro-server/public"
)

//
type ResponseCode int

// 1000 以上为自定义码
const (
	SUCCESS        ResponseCode = iota
	TOKEN_ERROR                 = 1001
	TIME_OUT                    = 1002
	PARMAS_ERROR                = 1003
	DATA_NOT_EXIST              = 1004
	RUN_ERROR                   = 1005
	DONE                        = 1006
)

var MsgFlags = map[ResponseCode]string{
	SUCCESS:        "success",
	TOKEN_ERROR:    "token错误",
	TIME_OUT:       "请求超时",
	PARMAS_ERROR:   "参数错误",
	DATA_NOT_EXIST: "数据不存在",
	RUN_ERROR:      "运行错误",
	DONE:           "已经处理",
}

type Response struct {
	ErrorCode ResponseCode `json:"errno"`
	ErrorMsg  string       `json:"errmsg"`
	Data      interface{}  `json:"data"`
	TraceId   interface{}  `json:"trace_id"`
}

func getErrorMsg(code ResponseCode, err error) string {
	errorMsg, ok := MsgFlags[code]
	if ok {
		if err != nil {
			return public.StringBuild(errorMsg, " ", err.Error())
		}
		return errorMsg
	}
	return ""
}

//
func ErrorOut(c *gin.Context, code ResponseCode, err error) {

	trace, _ := c.Get("trace")
	traceContext, _ := trace.(*lib.TraceContext)
	traceId := ""
	if traceContext != nil {
		traceId = traceContext.TraceId
	}

	data := make([]string, 0)
	resp := &Response{ErrorCode: code, ErrorMsg: getErrorMsg(code, err), Data: data, TraceId: traceId}

	c.JSON(200, resp)
	response, _ := json.Marshal(resp)
	c.Set("response", string(response))
	_ = c.AbortWithError(200, err)
	return
}

//
func SuccessOut(c *gin.Context, data interface{}, code ResponseCode) {
	trace, _ := c.Get("trace")
	traceContext, _ := trace.(*lib.TraceContext)
	traceId := ""
	if traceContext != nil {
		traceId = traceContext.TraceId
	}
	resp := &Response{ErrorCode: code, ErrorMsg: getErrorMsg(code, nil), Data: data, TraceId: traceId}
	c.JSON(200, resp)
	response, _ := json.Marshal(resp)
	c.Set("response", string(response))
	return
}
